package com.zjw.forum.services.impl;

import com.zjw.forum.common.AppResult;
import com.zjw.forum.common.ResultCode;
import com.zjw.forum.dao.ArticleMapper;
import com.zjw.forum.dao.UserMapper;
import com.zjw.forum.exception.ApplicationException;
import com.zjw.forum.model.User;
import com.zjw.forum.services.IUserService;
import com.zjw.forum.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    /**
     * 创建普通用户
     * @param user 用户信息
     * @return
     */
    @Override
    public void createNormalUser(User user) {
        //校验参数(注册信息中必填信息：用户名 密码 昵称)
        if(!StringUtils.hasLength(user.getUsername())||
                !StringUtils.hasLength(user.getPassword())||
        !StringUtils.hasLength(user.getNickname())){
            //为空，说明参数异常，必填的没填
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            //抛出异常，给统一异常管理处理
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检测用户名是否被注册了 （唯一性）
        User user1 = userMapper.selectUserByUserName(user.getUsername());
        //检测结果，如果不为null说明被注册了
        if(user1!=null){
            log.info(ResultCode.AILED_USER_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.AILED_USER_EXISTS));
        }

        //将选填信息通过代码，设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte) 0);
        Date date=new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);
        //未注册，将用户插入数据库中
        int i = userMapper.insertSelective(user);
        if(i!=1){
            //说明未插入
            log.warn(ResultCode.FAILED_CREATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        // 打印日志
        log.info("新用户成功. username = " + user.getUsername() + ". ");

    }

    @Override
    public User loginNromalUser(String username,String password) {
        //参数校验
        if(!StringUtils.hasLength(username)||
                !StringUtils.hasLength(password)){
            //为空，说明参数异常，必填的没填
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            //抛出异常，给统一异常管理处理
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检测用户名是否存在 （唯一性）
        User user1 = userMapper.selectUserByUserName(username);
        //检测结果，为null 说明不存在
        if(user1==null){
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //用户存在，开始校验密码是否正确
        //给密码进行MD5加密，和数据库中的密码比较
        if(!MD5Util.md5SaltVerify(password,user1.getPassword())){
            //密码错误
            log.info("密码错误");
            throw new ApplicationException(AppResult.failed("密码错误"));
        };
        return user1;
    }

    /**
     * 通过用户id获取用户信息
     * @param id 用户id
     * @return
     */
    @Override
    public User getUserinfo(Long id) {
        //参数校验
        if(id==null||id<=0){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //进行查询
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            //查询失败
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        log.info("查询成功！userId："+id);
        return user;
    }

    @Override
    public int addArticleCount(Long id) {
        //校验参数
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据userId，查询对应的user
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //查询到user，开始修改这个user的articlecount
        User user1=new User();
        user1.setId(user.getId());
        user1.setArticleCount(user.getArticleCount()+1);
        //更新 调用者对结果判断
        int i = userMapper.updateByPrimaryKeySelective(user1);
        return i;
    }

    @Override
    public int subArticleCount(Long id) {
        //校验参数
        if(id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据userId，查询对应的user
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //查询到user，开始修改这个user的articlecount
        User user1=new User();
        user1.setId(user.getId());
        user1.setArticleCount(user.getArticleCount()-1);
        //更新 调用者对结果判断
        if(user1.getArticleCount()<0){
            user1.setArticleCount(0);
        }
        int i = userMapper.updateByPrimaryKeySelective(user1);
        return i;
    }

    @Override
    public User updateUserInfo(User user) {
        //校验user是否为null、id是否合法
        if(user==null||user.getId()==null||user.getId()<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验user用户是否存在，不存在的话更新也会出错
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        if(user1==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //构造user对象，避免参数直接污染数据库
        User updateUser=new User();
        //在给user对象赋值时，要判断修改的属性是否全为空，如果全为空就没必要更新了，并且要判空，虽然是动态sql
        //标志位（如果到最后还为false说明属性全为空，不需要更新）
        Boolean checkAttr=false;
        //user是修改后的对象，user1是从数据库获取的对象。如果相同就不需要更新
        updateUser.setId(user.getId());
        //不为空并且与数据库的不相同才进行修改
        if(StringUtils.hasLength(user.getNickname())
                && !user.getNickname().equals(user1.getNickname())){
            //判断修改后的昵称是否存在
            User tmp = userMapper.selectUserByUserName(user.getNickname());
            if(tmp!=null){
                log.warn(ResultCode.FAILED_USER_UPDATE.getMessage());
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_UPDATE));
            }
            updateUser.setNickname(user.getNickname());
            checkAttr=true;
        }
        if(StringUtils.hasLength(user.getEmail())
                &&!user.getEmail().equals(user1.getEmail())){

            updateUser.setEmail(user.getEmail());
            checkAttr=true;
        }
        if(StringUtils.hasLength(user.getPhoneNum())
                &&!user.getPhoneNum().equals(user1.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr=true;
        }
        if(StringUtils.hasLength(user.getRemark())
                &&!user.getRemark().equals(user1.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr=true;
        }
        //属性全不需要更新，直接抛异常
        if(checkAttr==false){
            log.warn(ResultCode.FAILED_USER_UPDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_UPDATE));
        }
        //开始更新
        int i = userMapper.updateByPrimaryKeySelective(updateUser);
        if(i!=1){
            log.warn(ResultCode.FAILED.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        //把更新后的对象返回
        return updateUser;
    }

    /**
     * 修改密码
     * @param id
     * @param password
     */
    @Override
    public int updatePassword(Long id, String password) {
        //校验参数
        if(id==null||id<=0||!StringUtils.hasLength(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //给密码进行MD5加密
        String strPassword = MD5Util.md5SaltEncryption(password);
        //构造user，修改密码
        User user1=new User();
        user1.setId(id);
        user1.setPassword(strPassword);
        return userMapper.updateByPrimaryKeySelective(user1);
    }

}
